package org.satellite13.discountpack.client.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.satellite13.discountpack.client.android.R.id;
import org.satellite13.discountpack.model.JMessage;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;

public class MainActivity extends Activity {
	private int requestCode;
	private Account account = null;
	DefaultHttpClient http_client = new DefaultHttpClient();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		if (account == null) {
			final Intent intent = new Intent(this, AccountListActivity.class);
			requestCode = new Random().nextInt();
			startActivityForResult(intent, requestCode);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (this.requestCode == requestCode) {
			if (resultCode == RESULT_CANCELED) {
				finish();
				return;
			}
			AccountManager accountManager = AccountManager
					.get(getApplicationContext());
			account = (Account) data.getExtras().get("account");
			accountManager.getAuthToken(account, "ah", false,
					new GetAuthTokenCallback(), null);
		}
	}

	private class GetAuthTokenCallback implements
			AccountManagerCallback<Bundle> {
		public void run(AccountManagerFuture<Bundle> result) {
			Bundle bundle;
			try {
				bundle = result.getResult();
				Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
				if (intent != null) {
					startActivity(intent);
				} else {
					String auth_token = bundle
							.getString(AccountManager.KEY_AUTHTOKEN);
					new GetCookieTask().execute(auth_token);
				}
			} catch (OperationCanceledException e) {
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	};

	private class GetCookieTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... tokens) {
			try {
				// Don't follow redirects
				http_client.getParams().setBooleanParameter(
						ClientPNames.HANDLE_REDIRECTS, false);

				HttpGet http_get = new HttpGet(
						"https://discountpack.appspot.com/_ah/login?continue=http://localhost/&auth="
								+ tokens[0]);
				HttpResponse response = http_client.execute(http_get);
				if (response.getStatusLine().getStatusCode() != 302)
					// Response should be a redirect
					return false;
				for (Cookie cookie : http_client.getCookieStore().getCookies()) {
					if (cookie.getName().equals("SACSID"))
						return true;
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				http_client.getParams().setBooleanParameter(
						ClientPNames.HANDLE_REDIRECTS, true);
			}
			return false;
		}

		protected void onPostExecute(Boolean result) {
			if (result) {
				new AuthenticatedRequestTask()
						.execute("https://discountpack.appspot.com/TestServlet");
			} else {
				Log.e(this.getClass().getSimpleName(), "SACSID not found");
			}
		}
	}

	private class AuthenticatedRequestTask extends
			AsyncTask<String, Void, Void> {
		@Override
		protected Void doInBackground(String... urls) {
			try {
				HttpGet http_get = new HttpGet(urls[0]);
				BufferedReader reader;
				reader = new BufferedReader(new InputStreamReader(http_client
						.execute(http_get).getEntity().getContent()));
				Gson gson = new Gson();
				String line = reader.readLine();
				final JMessage jmsg = gson.fromJson(line, JMessage.class);
				runOnUiThread(new Runnable() {
					public void run() {
						((TextView) findViewById(id.textView1)).setText(jmsg
								.getMessage());
					}
				});
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

	}

}